<template>
  <tableLayout :columns="columns" :operationShow="true" :get="getData" :selectItem="selectItem" :rules="rules"
    ref="layout" :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }">

    <template #button>
      <a-button type="primary" style="margin-left: 20px" :disabled="selectedRowKeys.length !== 1"
        @click='fromDesigner'>设计</a-button>
      <a-button type="primary" style="margin-left: 20px" @click='add'>新增</a-button>
      <a-button style="margin-left: 20px" @click="edit" :disabled="selectedRowKeys.length !== 1">修改</a-button>
      <a-button type="primary" style="margin-left: 20px" :disabled="selectedRowKeys.length !== 1"
        @click='preview'>预览</a-button>
      <a-button style="margin-left: 20px" @click="refDataSource_click"
        :disabled="selectedRowKeys.length !== 1">映射字段</a-button>
      <a-button type="primary" style="margin-left: 20px" @click="del" :disabled="selectedRowKeys.length !== 1"
        danger>删除</a-button>
    </template>

    <template #operationMore="item">
      <a @click="edit(null, item.value.record)">编辑</a>
      <a-divider type="vertical" />
      <a @click="del(null, item.value.record.Id)">删除</a>
      <a-divider type="vertical" />
      <a @click="fromDesigner(null, item.value.record)">设计</a>
    </template>

    <template v-slot:custom="data">
      <a-input v-model:value="data.formData[data.key]" />
    </template>
  </tableLayout>

  <a-modal :title="formState.Id ? '编辑表单' : '新增表单'" v-model:visible="model_visible" :confirm-loading="confirmLoading"
    @ok="model_handleOk" width="900px">
    <a-form ref="formRef" :model="formState" :label-col="labelCol" :wrapper-col="wrapperCol" :rules="rules"
      layout="inline" class="comform">
      <a-form-item label="名称" style="width: calc(50% - 20px);" class="form__item" name="Name">
        <a-input v-model:value="formState.Name" placeholder="名称" />
      </a-form-item>
      <a-form-item label="表单编码" style="width: calc(50% - 20px);" class="form__item" name="FormCode">
        <a-input v-model:value="formState.FormCode" :readonly="true" placeholder="表单编码">
          <template #suffix>
            <a-tooltip title="复制表单编码">
              <CopyTwoTone style="color: rgba(0, 0, 0, 0.45)" @click="onCopyFormCode" />
            </a-tooltip>
          </template>
          <!-- <template #enterButton>
            <a-button @click="console.log(22222)">复制</a-button>
          </template> -->
        </a-input>
      </a-form-item>
      <a-form-item label="备注" style="width: calc(100% - 20px);" class="form__item" name="Description"
        :labelCol="{ span: 3 }" :wrapperCol="{ span: 21 }">
        <a-textarea v-model:value="formState.Description" placeholder="备注" :rows="4" />
      </a-form-item>
    </a-form>
  </a-modal>

  <a-modal title="设计表单" width="100%" v-model:visible="form_designer_visible" :confirm-loading="confirmLoading"
    wrapClassName="full-modal" @ok="formDesigner_handleOk">
    <div>
      <fc-designer ref="designer" style="height:calc(100vh - 156px)" @save="save" :config="config" />
    </div>
  </a-modal>
  <!--表单预览-->
  <a-modal title="表单预览" width="100%" v-model:visible="form_preview_visible" :confirm-loading="confirmLoading"
    :footer="null" wrapClassName="full-modal">
    <div>
      <form-create style="height:calc(100vh - 103px)" v-model="formData" v-model:api="fapi" :rule="rule"
        :option="options"></form-create>
    </div>
  </a-modal>

  <!-- 字段映射 -->
  <a-modal title="字段映射" width="1300px" v-model:visible="ref_datasource_visible" :confirm-loading="confirmLoading"
    @ok="formDataSourceRef_handleOk">
    <div>
      <div>
        <a-card title="数据源">
          <span>
            数据表:
          </span>
          <a-select v-model:value="tableSelected" style="width: 120px;" @change="tableSelectChange">
            <a-select-option v-for="item in tableOptions" :key="item.Id" :value="item.Id">
              {{ item.TableComments }}
            </a-select-option>
          </a-select>
          <span>
            字段:
          </span>
          <a-select v-model:value="columnsSelected" style="width: 120px;">
            <a-select-option v-for="item in columnsOptions" :key="item.Id" :value="item.Id">
              {{ item.Name }}
            </a-select-option>
          </a-select>
        </a-card>
      </div>
      <hr style="border-style: dashed;" />
      <a-table :columns="ref_table_columns" size="small" rowKey="Id" :data-source="refTableDataSource"
        :pagination="false" :scroll="{ y: 320 }" style="margin-top: 10px;" bordered>

        <template #operation="{ record }">
          <div class="editable-row-operations">
            <span>
              <a @click="dataSourceAssociation(record)">关联</a>
            </span>

            <span style="margin-left:10px;">
              <a @click="unbind(record)">解绑</a>
            </span>
          </div>
        </template>
      </a-table>
    </div>
  </a-modal>

</template>

<script lang="ts" setup>
import { notification, message } from 'ant-design-vue';
import tableLayout from '@/components/tableLayout/tableLayout.vue';
import { getData, delForm, addForm, updateForm, getlDataSourceColumns, getlDataSourceTables, saveOrUpdateFormDataSourceRef, getFormColumnRefDataSourceList } from '@/api/form/form';
import { ref, UnwrapRef, reactive, nextTick } from 'vue';
import { CopyTwoTone } from '@ant-design/icons-vue';
import { FormInput } from '@/types/api/form/form';
import { CustomIdPrefix } from '@/components/id/idGenerater';
import formCreate from "@form-create/element-ui";
import { json } from 'stream/consumers';
const layout = ref();
const model_visible = ref<boolean>(false);
const form_designer_visible = ref<boolean>(false);
const form_preview_visible = ref<boolean>(false);
const confirmLoading = ref<boolean>(false);
const formRef = ref()

//表单对象
const formState: UnwrapRef<FormInput> = reactive({
  Id: 0,
  Name: '',
  FormContent: '',
  Description: '',
  FormCode: '',
  Options: '',
  Rules: '',
});

//列表
const columns = [
  { title: '序号', dataIndex: 'Id' },
  { title: '名称', dataIndex: 'Name' },
  { title: '表单编码', dataIndex: 'FormCode' }
]

// 筛选
const selectItem = ref([
  { title: '名称', key: 'Name', type: 'input', itemWidth: '290px' },
  { title: '表单编码', key: 'FormCode', type: 'input', itemWidth: '290px' },
])

// 规则
const rules = ref()
const options = ref();

const add = () => {
  model_visible.value = true;
  let formCode = CustomIdPrefix("Form");
  Object.assign(formState, {
    Id: '',
    Name: '',
    FormContent: '',
    Description: '',
    FormCode: formCode,
    Options: '',
    Rules: '',
  });
}

// 编辑
const edit = (event: any, item: any) => {
  let selectItem = item;
  if (!selectItem) {
    if (!selectedRowKeys.value || selectedRowKeys.value.length <= 0 || selectedRowKeys.value.length > 1) {
      message.warning('请先选择一条数据!');
      return;
    }
    selectItem = selectedRows.value[0];
  }
  model_visible.value = true;
  Object.assign(formState, selectItem);
}

//删除
const del = (event: any, id: any) => {
  let selectId = id;
  if (!selectId) {
    if (!selectedRowKeys.value || selectedRowKeys.value.length <= 0 || selectedRowKeys.value.length > 1) {
      message.warning('请先选择一条数据!');
      return;
    }
    selectId = selectedRows.value[0].Id;
  }

  delForm({ Id: selectId }).then(() => {
    message.success("删除成功!");
    layout.value.getData();
  }).catch(err => {
    message.error(err.message || "删除失败!")
    confirmLoading.value = false;
  })
}

//复制表单编码
const onCopyFormCode = async (event: any) => {
  try {
    await navigator.clipboard.writeText(formState.FormCode);
    message.success('复制成功！');
  } catch (err) {
    console.error('复制失败', err);
    message.error('复制失败，请手动复制');
  }
}

// 多选
const selectedRowKeys = ref<any[]>([]);
const selectedRows = ref<any[]>([]);
const singleSelection = ref<any[]>([]);
const onSelectChange = (keys: [], rows: any) => {
  selectedRowKeys.value = keys;
  selectedRows.value = rows;
  singleSelection.value = rows[0];
}

const model_handleOk = () => {
  formRef.value.validate().then(() => {
    confirmLoading.value = true;
    let setForm = addForm;
    if (formState.Id) {
      setForm = updateForm;
    }
    setForm(formState).then(e => {
      message.success("操作成功！");
      confirmLoading.value = false;
      model_visible.value = false;
      layout.value.getData();
    }).catch(err => {
      message.error(err.message || "操作失败!")
      confirmLoading.value = false;
    })
  }).catch(() => {
    message.error('请检查必填项是否全部填写!');
  })
}

const formDesigner_handleOk = () => {
  confirmLoading.value = true;
  form_designer_visible.value = false;
  confirmLoading.value = false;
}

const labelCol = { span: 6 };
const wrapperCol = { span: 18 };

// 可以在此处获取设计器实例或进行其他操作
const designer = ref(null);
let designerItem: any;

/**
 * 获取数据
 * @param 表单数据
 * @returns
*/
const save = (formData: any) => {
  designerItem.FormContent = JSON.stringify(formData);
  designerItem.Rules = formData.rule;
  designerItem.Options = formData.options;
  updateForm(designerItem).then(e => {
    message.success("保存成功！");
    layout.value.getData();
  }).catch(err => {
    message.error(err.message || "保存失败!")
  })
}

const fromDesigner = (event: any, item: any) => {
  let selectItem = item;
  if (!selectItem) {
    if (!selectedRowKeys.value || selectedRowKeys.value.length <= 0 || selectedRowKeys.value.length > 1) {
      message.warning('请先选择一条数据!');
      return;
    }
    selectItem = selectedRows.value[0];
  }
  designerItem = selectItem;
  form_designer_visible.value = true;

  if (selectItem.FormContent) {
    nextTick(() => {
      designer.value.setRule(JSON.parse(selectItem.FormContent).rule);
      designer.value.setOption(JSON.parse(selectItem.FormContent).options);
    });
  }
}

const config = {
  showSaveBtn: true,
}

/**
 * 表单预览
 * @param 表单数据
 * @returns
*/
const preview = (event: any, item: any) => {
  let selectItem = item;
  if (!selectItem) {
    if (!selectedRowKeys.value || selectedRowKeys.value.length <= 0 || selectedRowKeys.value.length > 1) {
      message.warning('请先选择一条数据!');
      return;
    }
    selectItem = selectedRows.value[0];
  }

  form_preview_visible.value = true;
  rule.value = JSON.parse(selectItem.Rules);
  options.value = JSON.parse(selectItem.Options);
}

const rule = ref(formCreate.parseJson('[{"type":"input","field":"Ftqdm6ux66rxahc","title":"输入框","info":"","$required":false,"_fc_id":"id_Fyr0m6ux66rxaic","name":"ref_F9nem6ux66rxajc","display":true,"hidden":false,"_fc_drag_tag":"input"},{"type":"input","field":"F9itm6uy75vtabc","title":"多行输入框","info":"","$required":false,"props":{"type":"textarea"},"_fc_id":"id_Fsebm6uy75vtacc","name":"ref_Fye2m6uy75vtadc","display":true,"hidden":false,"_fc_drag_tag":"textarea"}]'));
const fapi = ref(null);
const formData = ref({});

/****************************字段映射******************************/

// 字段映射表格数据源
const refTableDataSource = ref([]);
const ref_datasource_visible = ref<boolean>(false);
const columnsOptions = ref([]);
const tableOptions = ref([]);
const tableSelected = ref<string | undefined>(undefined);
const columnsSelected = ref<string | undefined>(undefined);

// 字段映射按钮事件
const refDataSource_click = (event: any, item: any) => {
  let selectItem = item;
  if (!selectItem) {
    if (!selectedRowKeys.value || selectedRowKeys.value.length <= 0 || selectedRowKeys.value.length > 1) {
      message.warning('请先选择一条数据!');
      return;
    }
    selectItem = selectedRows.value[0];
  }
  ref_datasource_visible.value = true;

  getFormColumnRefDataSourceList({ formId: selectItem.Id }).then(e => {
    refTableDataSource.value = e.data.Data;
  }).catch(err => {
    console.log(err)
    message.error(err.message || "获取失败!")
  });

  getlDataSourceTables().then(e => {
    tableOptions.value = e.data.Data;
  }).catch(err => {
    console.log(err)
    message.error(err.message || "获取失败!")
  });
}



const tableSelectChange = (val: any) => {
  getlDataSourceColumns({ tableId: val }).then(e => {
    let data =e.data.Data;
    debugger
    //过来掉refTableDataSource 里面ColumnsId已经存在的数据
    refTableDataSource.value.forEach((item: any) => {
      data = data.filter((e: any) => e.Id != item.ColumnsId);
    });
    columnsOptions.value =data;
  }).catch(err => {
    console.log(err)
    message.error(err.message || "获取失败!")
  });
}
// 字段映射表格字段
const ref_table_columns = [
  { title: '表单字段', dataIndex: 'FormField' },
  { title: '表单标题', dataIndex: 'FormTitle' },
  { title: '表单类型', dataIndex: 'FormType', width: 100 },
  { title: '数据表编码', dataIndex: 'TableCode', width: 130 },
  { title: '数据表描述', dataIndex: 'TableComments', width: 150 },
  { title: '数据字段', dataIndex: 'Columns', width: 100 },
  { title: '数据字段名称', dataIndex: 'ColumnsName', width: 150 },
  // { title: '数据类型', dataIndex: 'DataType', width: 100 },
  // { title: '数据长度', dataIndex: 'DataLength', width: 100 },
  { title: '操作', dataIndex: 'operation', width: 120, slots: { customRender: 'operation' } }
]
const formDataSourceRef_handleOk = () => {
  confirmLoading.value = true;
  saveOrUpdateFormDataSourceRef(refTableDataSource.value).then(e => {
    message.success("保存成功！");
    ref_datasource_visible.value = false;
    confirmLoading.value = false;
  }).catch(err => {
    message.error(err.message || "保存失败!");
    confirmLoading.value = false;
  })
}

//关联
const dataSourceAssociation = (record:any) => {
  if(tableSelected.value == undefined || tableSelected.value == ""){
    message.warning('请选择数据表!');
    return;
  }

  if(columnsSelected.value == undefined || columnsSelected.value == ""){
    message.warning('请选择字段!');
    return; 
  }

  let table_record = tableOptions.value.find(e => e.Id == tableSelected.value);
  let columns_record = columnsOptions.value.find(e => e.Id == columnsSelected.value);
  record.TableName = table_record.TableName;
  record.TableComments = table_record.TableComments;
  record.TableCode = table_record.TableCode;
  record.TableId= table_record.Id;

  record.Columns = columns_record.Columns;
  record.ColumnsName = columns_record.Name;
  record.DataType = columns_record.DataType;
  record.DataLength = columns_record.DataLength;
  record.ColumnsId = columns_record.Id;

  if(tableOptions.value.length > 0){
    let tableId=tableSelected.value;
    columnsSelected.value = "";
    tableSelectChange(tableId);
  }
}

/**
 * 解绑
 * @param 表单数据
 * @returns
 */
const unbind = (record:any) => {
  record.TableName = "";
  record.TableCode = "";
  record.Columns = ""; 
  record.ColumnsName = "";
  record.DataType = "";
  record.DataLength = "";
  record.ColumnsId = "";
  record.TableId = "";

  if(tableOptions.value.length > 0){
    let tableId=tableSelected.value;
    columnsSelected.value = "";
    tableSelectChange(tableId);
  }
}
/****************************字段映射******************************/
</script>

<style lang="scss" scoped>
.full-modal {
  .ant-modal {
    max-width: 100%;
    top: 0;
    padding-bottom: 0;
    margin: 0;

  }



  .ant-modal-body {
    flex: 1;
  }
}

.comform {
  & .form__item {
    margin-bottom: 16px;

    & .ant-form-item-label {
      flex-grow: 1 !important;
      flex-shrink: 0;
    }
  }
}
</style>
<style lang="scss">
.full-modal {
  .ant-modal {
    max-width: 100%;
    top: 0;
    padding-bottom: 0;
    margin: 0;

  }



  .ant-modal-body {
    flex: 1;
  }
}

.comform {
  & .form__item {
    margin-bottom: 16px;

    & .ant-form-item-label {
      flex-grow: 1;
      flex-shrink: 0;
    }
  }
}
</style>